package main

import (
	"fmt"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strings"
)

const (
	UPLOAD_DIR = "./uploads"
)

//启动一个简单的web服务
func main() {
	fmt.Println("examp22")
	// 设置访问的路由
	http.HandleFunc("/", sayhelloName)        //参数是访问地址和函数
	http.HandleFunc("/upload", uploadHandler) //上传文件
	http.HandleFunc("/list", listHandler)     //显示文件列表
	// 设置监听的端口
	err := http.ListenAndServe(":9090", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

func sayhelloName(w http.ResponseWriter, r *http.Request) {
	// 解析参数, 默认是不会解析的
	r.ParseForm()
	// 这些信息是输出到服务器端的打印信息
	fmt.Println("request map:", r.Form)
	fmt.Println("path", r.URL.Path)
	fmt.Println("scheme", r.URL.Scheme)
	fmt.Println(r.Form["url_long"])
	for k, v := range r.Form {
		fmt.Println("key:", k)
		fmt.Println("val:", strings.Join(v, ";"))
	}
	// 这个写入到w的信息是输出到客户端的
	fmt.Fprintf(w, "Hello,World!")
}

func uploadHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		t, _ := template.ParseFiles("upload.html")
		t.Execute(w, nil)
	} else {
		f, h, _ := r.FormFile("image")
		filename := h.Filename
		defer f.Close()
		t, _ := os.Create(UPLOAD_DIR + "/" + filename)
		defer t.Close()
		_, err := io.Copy(t, f)
		if err != nil {
			return
		}
		http.Redirect(w, r, "list?id="+filename, http.StatusFound)
	}
}

func listHandler(w http.ResponseWriter, r *http.Request) {
	fileInfoArr, _ := ioutil.ReadDir(UPLOAD_DIR)
	locals := make(map[string]interface{})
	images := []string{}
	for _, fileInfo := range fileInfoArr {
		images = append(images, fileInfo.Name())
	}
	locals["images"] = images
	t, _ := template.ParseFiles("list.html")
	t.Execute(w, locals)
}
